package com.zhengaz.common.security.feign;


import com.zhengaz.common.core.constant.SecurityConstants;
import com.zhengaz.common.core.exception.InnerAuthException;
import com.zhengaz.common.core.utils.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.Optional;

/**
 * feign 请求拦截器
 *
 * @author zhengzg
 * @create 2023-09-07 17:46
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        Optional.ofNullable(attributes).orElseThrow(() -> new InnerAuthException("没有设置用户信息，不允许访问 "));
        HttpServletRequest httpServletRequest = attributes.getRequest();


        Map<String, String> headers = new LinkedCaseInsensitiveMap<>();
        Enumeration<String> enumeration = httpServletRequest.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = httpServletRequest.getHeader(key);
                headers.put(key, value);
            }
        }
        // 传递用户信息请求头，防止丢失
        String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
        if (StringUtils.isNotEmpty(userId)) {
            requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
        }
        String userKey = headers.get(SecurityConstants.USER_KEY);
        if (StringUtils.isNotEmpty(userKey)) {
            requestTemplate.header(SecurityConstants.USER_KEY, userKey);
        }
        String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
        if (StringUtils.isNotEmpty(userName)) {
            requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
        }
        String authentication = headers.get(SecurityConstants.AUTHORIZATION_HEADER);
        if (StringUtils.isNotEmpty(authentication)) {
            requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);
        }

        // 配置客户端IP
        requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr());

    }
}